import pymysql
from Common.handle_config import conf

"""
1.初始化数据库，连接数据库，创建游标
2.查询一条数据
3.查询全部

"""


class HandleDB:
    def __init__(self):
        # 连接数据库，创建游标。
        # 1、建立连接
        self.conn = pymysql.connect(
            host=conf.get("db", "mysql_host"),
            port=int(conf.get("db", "mysql_port")),
            user=conf.get("db", "mysql_user"),
            password=conf.get("db", "mysql_password"),
            database=conf.get("db", "mysql_database"),
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor
        )
        # 2、创建游标
        self.cur = self.conn.cursor()

        # 查询一条数据

    def select_one_data(self, sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchone()

        # 查询全部

    def select_all_data(self, sql):
        self.conn.commit()
        self.cur.execute(sql)
        return self.cur.fetchall()

        # 查询条数

    def select_count(self, sql):
        self.conn.commit()
        return self.cur.execute(sql)

    def update(self, sql):
        """
        对数据库进行增、删、改的操作。
        :param sql:执行的mysql语句
        :return:
        """
        self.cur.execute(sql)
        self.conn.commit()

        # 关闭连接

    def close(self):
        self.cur.close()
        self.conn.close()


if __name__ == '__main__':
    sql = "SELECT * FROM futureloan.member limit 3 "
    db = HandleDB()
    # re=db.select_one_data(sql)
    re2 = db.select_all_data(sql)
    print(re2)
    re3 = db.select_count(sql)
    print(re3)
